<template>
  <XhhTable
    ref="table"
    :columns="columns"
    :api="api"
    :form-config="formConfig"
    :params="formConfig.form"
    unique-id="role-list-table"
    :is-pagination="false"
    stripe
    checkbox
    :row-class-name="handleRowClassName"
    :importConfig="importConfig"
    :emitDialogList="['add']"
    @delete="handleDelete"
    @del="handleDel"
    @disableRow="handleDisableRow"
    @enableRow="handleEnableRow"
    @export="handleExport"
    @editRole="handleEditRole"
    @add="handleAdd"
  ></XhhTable>
  <XhhDialog
    v-if="dialogVisible"
    v-model="dialogVisible"
    :title="dialogTitle"
    v-bind="formConfig.dialogProps"
  >
    <XhhForm
      ref="dialogFormRef"
      :schema="formConfig.dialogSchema"
      v-model="dialogFormValue"
      :inline="false"
      v-bind="formConfig.dialogFormProps"
      :showFormButton="false"
      :defaultSearch="false"
      :isGrid="true"
    ></XhhForm>
  </XhhDialog>
</template>
<script setup>
import { ref, h, onMounted } from 'vue'
import req from '@/utils/req/axios'
import { ElCascader, ElButton } from 'element-plus'
import { tip, tipBox } from '@tip'
import { requiredRule } from '@/utils/common/form'
import urls from '@/utils/constants/urls.js'
import { downloadFile } from '@/utils/common/window/index.js'
import { showOverflowTooltip } from '@/utils/constants/utils'
import { buildTree } from '@/utils/common/fns/array'
import { XhhSelect } from 'xhh-design'
import allSvg from '@/assets/img/all.svg'
import { userListSelectProps } from '@/utils/common/user/form'

// todo 根据角色添加资源，角色添加人员

const dialogVisible = ref(false)
const dialogFormValue = ref({})
const dialogTitle = ref('新增角色')
const resourceOptions = ref([])
// const userOptions = ref([])
const dialogFormMode = ref('add')
const table = ref()
const dialogFormRef = ref()
const resourceOriginData = ref([])
const userOriginData = ref([])
const showUserSelect = ref(true)

onMounted(async () => {
  loadResourceOptions()
  loadUserList()
})

const columns = ref([
  {
    prop: 'roleName',
    label: '角色名称',
    width: 120,
  },
  {
    prop: 'roleCode',
    label: '角色编码',
    width: 120,
  },
  {
    prop: 'resourceList',
    label: '资源列表',
    ...showOverflowTooltip,
    slots: {
      default(scope) {
        return h('span', {}, [
          ...(resourceOriginData.value.length === scope.row.resourceList.length
            ? [h('img', { src: allSvg, class: 'mr5' })]
            : []),
          h(
            'span',
            {},
            { default: () => scope.row.resourceList.map((item) => item.name).join('，') },
          ),
        ])
      },
    },
  },
  {
    prop: 'userList',
    label: '人员列表',
    ...showOverflowTooltip,
    slots: {
      default(scope) {
        return h('span', {}, [
          ...(userOriginData.value.length === scope.row.userList.length
            ? [h('img', { src: allSvg, class: 'mr5' })]
            : []),
          h('span', {}, { default: () => scope.row.userList.map((item) => item.name).join('，') }),
        ])
      },
    },
  },
  {
    prop: 'op',
    label: '操作',
    buttons({ row }) {
      console.log('row.status', row)
      return [
        'delete',
        {
          prop: 'editRole',
          label: '编辑',
          type: 'primary',
        },
        {
          // status 1 表示已启用 其他表示已停用
          prop: row.status === '1' ? 'disableRow' : 'enableRow',
          label: row.status === '1' ? '停用' : '启用',
          class: row.status === '1' ? 'red' : 'green',
        },
      ]
    },
    width: 270,
  },
])
const api = {
  async request(params) {
    // 此页面暂时不进行分页
    const { total, data } = await req.post(urls.v1.system.role.list, {
      ...params,
      status: '',
    })
    return {
      total,
      data,
    }
  },
}
const formConfig = ref({
  form: {},
  schema: [
    {
      prop: 'roleName',
      label: '角色名称',
    },
    {
      prop: 'roleCode',
      label: '角色编码',
    },
    {
      prop: 'userList',
      label: '用户',
      comp: 'select',
      props: {
        'collapse-tags': true,
        class: 'select-line w140',
        ...userListSelectProps,
      },
    },
    {
      prop: 'resourceList',
      label: '资源',
      comp: 'ElCascader',
      props: {
        options: [],
        class: 'cascader-line w200',
        clearable: true,
        'show-all-levels': false,
        'collapse-tags': true,
        filterable: true,
        props: {
          multiple: true,
          emitPath: false,
          value: 'id',
          checkStrictly: true,
        },
      },
    },
  ],
  queryFormProps: {},
  // 如果配置了dialogForm，则使用默认的新增弹窗
  // dialogForm: {},
  dialogSchema: [
    {
      prop: 'roleName',
      label: '角色名称',
    },
    {
      prop: 'roleCode',
      label: '角色编码',
    },
    {
      prop: 'resourceList',
      label: '资源列表',
      comp: 'slot',
      colProps: {
        span: 24,
      },
      render() {
        return h('div', { class: 'flex-div' }, [
          h(ElCascader, {
            modelValue: dialogFormValue.value.resourceList,
            'onUpdate:modelValue': (val) => {
              dialogFormValue.value.resourceList = val
            },
            options: resourceOptions.value,
            class: 'w',
            clearable: true,
            'show-all-levels': false,
            filterable: true,
            props: {
              multiple: true,
              emitPath: false,
              value: 'id',
              checkStrictly: true,
            },
          }),
          h(
            ElButton,
            {
              type: 'text',
              onClick() {
                if (dialogFormValue.value.resourceList.length === resourceOriginData.value.length) {
                  // 已经全选，点击之后，将清空
                  dialogFormValue.value.resourceList = []
                } else {
                  dialogFormValue.value.resourceList = resourceOriginData.value.map(
                    (item) => item.id,
                  )
                }
              },
            },
            {
              default: () =>
                dialogFormValue.value?.resourceList?.length === resourceOriginData.value.length
                  ? '取消全选'
                  : '全选',
            },
          ),
        ])
      },
    },
    // 一次性获取全部人员列表
    // {
    //   prop: 'userList',
    //   label: '人员列表',
    //   comp: 'XhhSelect',
    //   colProps: {
    //     span: 24,
    //   },
    //   props: {
    //     modelValue: dialogFormValue.value.userList,
    //     'onUpdate:modelValue': (val) => {
    //       dialogFormValue.value.userList = val
    //     },
    //     options: [],
    //     multiple: true,
    //     filterable: true,
    //     optionMap: {label: 'userName', value: 'id'},
    //   },
    // },
    // 人员过多时使用远程获取
    // {
    //   prop: 'userList',
    //   label: '人员列表',
    //   comp: 'XhhSelect',
    //   colProps: {
    //     span: 24,
    //   },
    //   props: {
    //     modelValue: dialogFormValue.value.userList,
    //     'onUpdate:modelValue': (val) => {
    //       dialogFormValue.value.userList = val
    //     },
    //     multiple: true,
    //     filterable: true,
    //     remote: true,
    //     optionMap: {label: 'userName', value: 'id'},
    //     api: {
    //       async request(query) {
    //         const res = await req.post(urls.v1.system.user.list, {
    //           pageSize: 20,
    //           ...(query ? {userName: query} : {}),
    //         })
    //         return res.data
    //       },
    //       async loadByIdRequest(value) {
    //         const res = await req.post(urls.v1.system.user.getById, {
    //           id: value,
    //         })
    //         return res.data
    //       },
    //     },
    //   },
    // },
    // 增加全选功能
    {
      prop: 'userList',
      label: '人员列表',
      comp: 'slot',
      colProps: {
        span: 24,
      },
      render() {
        return h('div', { class: 'flex-div' }, [
          ...(showUserSelect.value
            ? [
                h(XhhSelect, {
                  modelValue: dialogFormValue.value.userList,
                  'onUpdate:modelValue': (val) => {
                    dialogFormValue.value.userList = val
                  },
                  ...userListSelectProps,
                }),
              ]
            : []),
          h(
            ElButton,
            {
              type: 'text',
              onClick() {
                if (dialogFormValue.value.userList.length === userOriginData.value.length) {
                  // 已经全选，点击之后，将清空
                  dialogFormValue.value.userList = []
                } else {
                  dialogFormValue.value.userList = userOriginData.value.map((item) => item.id)
                  showUserSelect.value = false
                  setTimeout(() => {
                    showUserSelect.value = true
                  }, 100)
                }
              },
            },
            {
              default: () =>
                dialogFormValue.value.userList.length === userOriginData.value.length
                  ? '取消全选'
                  : '全选',
            },
          ),
        ])
      },
    },
  ],
  dialogFormProps: {
    // dev13及以后可以删除此属性
    defaultSearch: false,
    rules: {
      ...requiredRule('roleName'),
      ...requiredRule('roleCode'),
    },
  },
  dialogProps: {
    async onConfirm() {
      // todo 验证表单
      await dialogFormRef.value.$refs.formRef.validate()
      // 如果验证失败，直接就在内部抛出错误了，下边的代码不会走了
      // 获取表单数据
      // 整理表单数据
      // 表单数据

      const params = {
        ...dialogFormValue.value,
      }
      let url
      // 发送请求
      if (dialogFormMode.value === 'add') {
        // 新增
        url = urls.v1.system.role.add
        params.status = '1'
      } else if (dialogFormMode.value === 'edit') {
        // 编辑
        url = urls.v1.system.role.update
      }
      await req.post(url, params)
      // 关闭弹窗
      dialogVisible.value = false
      // 刷新列表
      table.value.searchData(true)
    },
  },
})

const importConfig = {
  api: {
    async requestTemplate() {
      const res = await req.post(
        urls.v1.system.role.exportTemplate,
        {},
        {
          responseType: 'blob',
        },
      )
      return res.data
    },
    requestImport(formData, headers) {
      return req.post(urls.v1.system.role.import, formData, {
        headers,
        _isReturnOrigin: true,
      })
    },
  },
}

function setEditDialog({ props, scope }) {
  props.dialogForm.value = scope.row
}

/**
 * 单个删除
 * @param row
 * @returns {Promise<void>}
 */
async function handleDelete({ row }) {
  await req.post(urls.v1.system.role.del, { id: row.id })
  table.value.searchData(true)
}

/**
 * 批量删除
 * @returns {Promise<void>}
 */
async function handleDel() {
  if (!table.value.checkedRows?.length) {
    tip({ message: '请选择要删除的行', type: 'error' })
    return
  }
  await req.post(urls.v1.system.role.del, {
    ids: table.value.checkedRows.map((item) => item.id),
  })
  table.value.searchData()
}

/**
 * 导出excel
 * @returns {Promise<void>}
 */
async function handleExport() {
  const dataLength = table.value.checkedRows?.length
  // 若存在选中的数据，则导出选中的数据，否则按条件导出数据
  const confirm = await tipBox.confirm(
    dataLength ? `确认要导出选中的${dataLength}条数据吗？` : `确认要根据查询条件导出数据吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  if (confirm === 'confirm') {
    // 查询条件
    const res = await req.post(
      urls.v1.system.role.export,
      {
        ...(dataLength
          ? { ids: table.value.checkedRows.map((item) => item.id) }
          : { ...table.value.queryForm }),
      },
      { responseType: 'blob' },
    )
    // 将流转化为文件进行下载 todo 文件名称从后端获取，从headers中获取
    downloadFile({ blob: res.data, fileName: '权限列表.xlsx' })
  }
}

async function handleStatusRow({ row, status, message, label }) {
  const confirm = await tipBox.confirm(`确认要执行${label}操作吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  if (confirm === 'confirm') {
    await req.post(urls.v1.system.role.update, { id: row.id, status }, { _showSuccessTip: false })
    tip({ message, type: 'success' })
    table.value.searchData(true)
  }
}

async function handleDisableRow({ row }) {
  await handleStatusRow({ row, status: '2', message: '停用成功', label: '停用' })
}

async function handleEnableRow({ row }) {
  await handleStatusRow({ row, status: '1', message: '启用成功', label: '启用' })
}

function handleRowClassName({ row }) {
  return row.status === '1' ? 'enable-row' : 'disable-row'
}

function handleEditRole({ row }) {
  dialogFormMode.value = 'edit'
  dialogFormValue.value = {
    ...row,
    resourceList: row.resourceList.map((item) => item.id),
    userList: row.userList.map((item) => item.id),
  }
  dialogVisible.value = true
}

async function loadResourceOptions() {
  const { data } = await req.post(urls.v1.system.resource.list, {
    status: '',
  })
  resourceOriginData.value = data
  resourceOptions.value = buildTree(data)
  const resourceListItem = formConfig.value.schema.find((item) => item.prop === 'resourceList')
  resourceListItem.props.options = resourceOptions.value
}

async function loadUserList() {
  const { data } = await req.post(urls.v1.system.user.list, {
    isPagination: false,
  })
  userOriginData.value = data
}

function handleAdd() {
  dialogFormMode.value = 'add'
  dialogFormValue.value = {}
  dialogVisible.value = true
}

// async function loadUserOptions() {
//   const {data} = await req.post(urls.v1.system.user.list, {
//     pageSize: 10000,
//     status: '',
//   })
//   // userOptions.value = data
//   formConfig.dialogSchema.find(item => item.prop === 'userList').props.options = data
// }
</script>
